import os
import re
import asyncio
import click
from playwright.async_api import async_playwright

async def download_pdfs(volume, issue, download_dir="pdf_downloads"):
    """下载指定卷数和期数的PDF文件"""
    os.makedirs(download_dir, exist_ok=True)
    
    # 构建URL
    url = f"http://www.bulletin.cas.cn/BCAS_CH/issue/{volume}/{issue}"
    print(f"准备下载: 卷{volume}期{issue} ({url})")
    
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()
        
        try:
            await page.goto(url)
            print(f"已访问页面: {url}")
            
            # 等待文章列表加载完成
            await page.wait_for_selector('.actriveList', timeout=60000)
            print("文章列表已加载")
            
            # 获取所有文章项
            articles = await page.query_selector_all('.actriveList')
            print(f"找到 {len(articles)} 篇文章")
            
            for i, article in enumerate(articles):
                try:
                    # 获取文章标题
                    title_element = await article.query_selector('.title span')
                    title = await title_element.text_content()
                    title = title.strip()
                    
                    # 清理文件名中的非法字符
                    safe_filename = re.sub(r'[\\/*?:"<>|]', "", title)
                    safe_filename = re.sub(r'\s+', ' ', safe_filename)
                    
                    # 在文章项中查找下载PDF按钮
                    download_button = await article.query_selector('.labelBox .imgText:has-text("下载 PDF")')
                    
                    if download_button:
                        print(f"处理文章 {i+1}/{len(articles)}: {title}")
                        
                        # 设置下载路径
                        save_path = os.path.join(download_dir, f"{safe_filename}.pdf")
                        
                        # 处理下载
                        async with page.expect_download() as download_info:
                            await download_button.click()
                        download = await download_info.value
                        
                        # 保存文件
                        await download.save_as(save_path)
                        print(f"已下载: {save_path}")
                    else:
                        print(f"未找到文章 {i+1} 的下载按钮: {title}")
                
                except Exception as e:
                    print(f"处理文章 {i+1} 时出错: {str(e)}")
                    continue
            
            print(f"卷{volume}期{issue}的所有文章处理完成")
            
        except Exception as e:
            print(f"访问页面时出错: {str(e)}")
        finally:
            await browser.close()

@click.command()
@click.option('--volume', '-v', default=40, type=int, help='期刊卷数')
@click.option('--issue', '-i', default=5, type=int, help='期刊期数')
@click.option('--output', '-o', default='pdf_downloads', help='保存目录')
def main(volume, issue, output):
    """下载中国科学院院刊指定卷数和期数的PDF文件"""
    print(f"开始下载: 卷{volume}期{issue}")
    asyncio.run(download_pdfs(volume, issue, f"{output}_{volume}_{issue}"))
    print("下载任务完成")

if __name__ == "__main__":
    main()
